package com.gitee.wsl.logger.cash

import com.gitee.wsl.logger.Logger

/**
 * 线程崩溃的异常捕获
 */
abstract class BaseCrashStrategy: Thread.UncaughtExceptionHandler{

    /*** 系统默认的UncaughtException处理类  */
    private var mDefHandler: Thread.UncaughtExceptionHandler? = null

    open fun init(){
        if(mDefHandler==null) {
            mDefHandler = Thread.getDefaultUncaughtExceptionHandler()
            Thread.setDefaultUncaughtExceptionHandler(this)
        }
    }

    /**
     * 获取系统默认的 UncaughtExceptionHandler
     * @return
     */
    protected fun getDefaultUncaughtExceptionHandler(): Thread.UncaughtExceptionHandler? {
        return mDefHandler
    }

}

/**
 * 默认异常捕获机制
 * - 发生异常会自动捕获异常，打印到日志文件
 */
class DefaultCrashStrategyImpl: BaseCrashStrategy() {

    override fun uncaughtException(t: Thread, e: Throwable) {
        Logger.e("crash exception：${Thread.currentThread().name}")
        Logger[TAG].e("Thread (${t.name}) crashed ",e)
        getDefaultUncaughtExceptionHandler()?.uncaughtException(t,e)
    }

    companion object{
        private const val TAG = "[crash]"
        val instance = DefaultCrashStrategyImpl()
        fun setup(){
            instance.init()
        }
    }

}

fun Logger.ableCashThread():Logger {
    DefaultCrashStrategyImpl.setup()
    return this
}